import time
import subprocess
import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont

# 创建I2C接口

# Raspberry Pi pin configuration:
RST = 24
# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# 创建OLED显示器对象 (128x64)
display = Adafruit_SSD1306.SSD1306_128_64(RST)
display.begin()


def get_network_info():
    # 获取SSID
    try:
        cmd = "iwgetid -r"
        ssid = subprocess.check_output(cmd, shell=True).decode('utf-8').strip()
    except:
        ssid = "No WiFi Connected."
    
    # 获取IP地址
    try:
        cmd = "hostname -I"
        ip = subprocess.check_output(cmd, shell=True).decode('utf-8').split()[0]
    except:
        ip = "No IP Addr"
    
    return ssid, ip

def display_info():
    # 创建空白图像
    image = Image.new("1", (128, 64))
    draw = ImageDraw.Draw(image)
#    draw.rectangle((0,0,128,64),outline=0,fill=0)
    
    # 加载字体
    try:
        font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 12)
    except:
        font = ImageFont.load_default()
    
    while True:
        # 获取网络信息
        ssid, ip = get_network_info()
        
        # 清除显示
        display.clear()
        draw.rectangle((0,0,128,64),outline=0,fill=0)
#        display.display()
        
        # 绘制文本
        draw.text((0, 0), "WiFi :", font=font, fill=255)
        draw.text((0, 16), ssid, font=font, fill=255)
        draw.text((0, 32), "IP :", font=font, fill=255)
        draw.text((0, 48), ip, font=font, fill=255)
        
        # 显示图像cc
        display.image(image)
        display.display()
        
        # 每5秒更新一次
        time.sleep(5)

if __name__ == "__main__":
    try:
        display_info()
    except KeyboardInterrupt:
        display.clear()
        display.display()
